package com.biz.primus.ms.order.util;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

/**
 * EnumUtil
 *
 * @author Tiger Feng
 * @date 2017年11月24日
 */
public class EnumUtil {
    /**
     * 获取枚举名称与描述的字典
     *
     * @param clz 枚举类
     * @return 枚举名称与描述的字典
     * @throws Exception
     */
    public static Map<String, String> toMap(Class clz) throws Exception {
        Map<String, String> map = Maps.newHashMap();
        Field[] fs = clz.getDeclaredFields();

        // key
        List<String> enumNames = Lists.newArrayList();
        // value的变量名
        String keyFieldName = null;
        // value，没有描述的字段时显示此字段
        String keyFieldNameOther = null;

        for (int i = 0; i < fs.length; i++) {
            Field f = fs[i];
            //设置些属性是可以访问的
            f.setAccessible(true);
            //得到此属性的值
            AnnotatedType at = f.getAnnotatedType();
            String type = f.getType().getName();
            switch (type) {
                case "java.lang.String":
                    if (keyFieldName == null || "".equals(keyFieldName)) {
                        keyFieldName = f.getName();
                    }
                    break;
                case "java.lang.Integer":
                    if (keyFieldNameOther == null || "".equals(keyFieldNameOther)) {
                        keyFieldNameOther = f.getName();
                    }
                    break;
                case "int":
                    if (keyFieldNameOther == null || "".equals(keyFieldNameOther)) {
                        keyFieldNameOther = f.getName();
                    }
                    break;
                default:
                    if (!f.getName().contains("$")) {
                        enumNames.add(f.getName());
                    }
                    break;
            }
        }
        String mn = getMethod(keyFieldName == null ? keyFieldNameOther : keyFieldName);
        for (String enumName : enumNames) {
            if(mn == null || "".equals(mn)){
                map.put(enumName,"");
            }else{
                Enum e = Enum.valueOf(clz, enumName);
                Method m1 = clz.getMethod(mn);
                map.put(enumName, m1.invoke(e).toString());
            }
        }
        return map;
    }

    private static String getMethod(String fieldName) {
        if (fieldName == null || "".equals(fieldName)) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        sb.append("get");
        sb.append(fieldName.substring(0, 1).toUpperCase());
        sb.append(fieldName.substring(1));
        return sb.toString();
    }

}
